import {messages, getQueryUrlParam} from "share/common";
import React from 'react'
import {connect} from "react-redux";
import { message, Icon, Form, Modal, Button, Row, Col, Input, Radio } from 'antd'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
import Chooser from 'components/chooser'
import approveService from 'containers/approve/approve.service'
import errorMessage from 'share/errorMessage';

class ApproveAdditional extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    }
  }

  componentWillMount() {}

  componentWillReceiveProps(nextProps) {
    const { additionalVisible, form } = this.props;
    if (!additionalVisible && nextProps.additionalVisible) {
      form.resetFields();
    }
  }

  //isSuccess 是否是成功的返回
  //type backward 向后加签 forward 向前加签
  //params 向后加签要更新的参数，要刷新外层的加签人和审批意见
  closeAdditionalModal = (isSuccess, type, params) => {
    const { onClose } = this.props;
    if (onClose) {
      onClose(isSuccess, type, params);
    }
  };

  handleAdditional = () => {
    const { entities } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        //向后加签逻辑
        if (values.sequence === 'backward') {
          this.closeAdditionalModal(true, 'backward', {selectedData: values.person, quickTxt: values.reason});
        }
        //向前加签逻辑
        if (values.sequence === 'forward') {
          let additionalOIDs = [];
          values.person.map(person => {
            additionalOIDs.push(person.userOID);
          });
          let params = {
            entities: [{
              approverOID: entities.approverOID,
              entityOID: entities.entityOID,
              entityType: entities.entityType,
              countersignApproverOIDs: additionalOIDs
            }],
            approvalTxt: values.reason
          };
          this.setState({loading: true});
          approveService.postForwardAdditional(params).then(res => {
            if (res.data.failNum === 0) {
              message.success(messages('common.operate.success'));
              this.closeAdditionalModal(true, 'forward');
            } else {
              message.error(`${messages('common.operate.filed')}，${res.data.failReason[entities.entityOID]}`)
            }
          }).catch(e => {
            errorMessage(e.response);
          }).finally(() => {
            this.setState({loading: false});
          });
        }
      }
    });
  };

  //处理加签顺序的文字描述
  //type backward 向后加签 forward 向前加签
  renderSequenceTxt = (type) => {
    const { customFormPropertyMap } = this.props;
    let txt = '';
    if (type === 'backward') {
      switch(customFormPropertyMap.countersignType) {
        case '0':
          txt = messages('components.key980')/*我审批通过后再由加签人一起审批*/;
          break;
        case '1':
          txt = messages('components.key981')/*我审批通过后再由加签人任一审批*/;
          break;
        case '2':
          txt = messages('components.key982')/*我审批通过后再由加签人按序审批*/;
          break;
      }
    }
    if (type === 'forward') {
      switch(customFormPropertyMap.countersignType) {
        case '0':
          txt = messages('components.key983')/*加签人全部通过后再由我审批*/;
          break;
        case '1':
          txt = messages('components.key984')/*加签人任一通过后再由我审批*/;
          break;
        case '2':
          txt = messages('components.key985')/*加签人按序通过后再由我审批*/;
          break;
      }
    }
    return txt;
  };

  render() {
    const { additionalVisible, customFormPropertyMap, selectedData, quickTxt } = this.props;
    const { loading } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 19 },
    };
    let signCompanyOIDs = (customFormPropertyMap && customFormPropertyMap['approval_add_sign_scope']) ? JSON.parse(customFormPropertyMap['approval_add_sign_scope']).companyOIDs : [];
    return (
      <div>
        <Modal
          width={700}
          title={messages('components.key434')/*加签*/}
          visible={additionalVisible}
          onCancel={() => this.closeAdditionalModal(false)}
          maskClosable={false}
          destroyOnClose={true}
          footer={[
            <Button key="back" onClick={() => this.closeAdditionalModal(false)}>{messages('common.cancel')/*取消*/}</Button>,
            <Button key="submit" type="primary" loading={loading} onClick={() => this.handleAdditional()}>{messages('common.ok')/*确定*/}</Button>
          ]}
        >
          <Form>
            <FormItem {...formItemLayout} label={messages('components.key986')/*加签给*/}>
              {getFieldDecorator('person', {
                rules: [
                  {
                    required: true,
                    message: messages('common.please.select') //请选择
                  }
                ],
                initialValue: selectedData
              })(
                <Chooser
                  placeholder={messages('common.please.select')/*请选择*/}
                  type='user'
                  labelKey='fullName'
                  valueKey='userOID'
                  listExtraParams={{
                    roleType: 'TENANT',
                    corporationOID: signCompanyOIDs,
                    companyOID: signCompanyOIDs
                  }}
                  showNumber={false}
                  newline
                  showDetail
                />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('components.key987')/*加签顺序*/}>
              {getFieldDecorator('sequence', {
                initialValue: 'backward'
              })(
                <RadioGroup>
                  <Radio value="backward" style={{display: 'block', minHeight: 31, lineHeight: '31px'}}>
                    <span style={{whiteSpace: 'normal'}}>
                      {messages('components.key988')/*向后加签*/}&nbsp;
                      <span>{this.renderSequenceTxt('backward')}</span>
                    </span>
                  </Radio>
                  <Radio value="forward" style={{display: 'block', minHeight: 31, lineHeight: '31px'}}>
                    <span style={{whiteSpace: 'normal'}}>
                      {messages('components.key989')/*向前加签*/}&nbsp;
                      <span>{this.renderSequenceTxt('forward')}</span>
                    </span>
                  </Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={messages('components.key990')/*加签意见*/}>
              {getFieldDecorator('reason', {
                rules: [
                  {
                    max: 500,
                    message: messages('common.max.characters.length', {max: 500})
                  }
                ],
                initialValue: quickTxt
              })(
                <TextArea rows={4} placeholder={messages('components.key991')/*加签意见，最多输入500个字符*/} style={{resize: 'none'}} />
              )}
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
}

ApproveAdditional.propTypes = {
  additionalVisible: React.PropTypes.bool,
  selectedData: React.PropTypes.array,  //已选的加签人数据
  quickTxt: React.PropTypes.string, //审批意见
  onClose: React.PropTypes.func,
  entities: React.PropTypes.object,//审批加签所需字段
  customFormPropertyMap: React.PropTypes.object
};

ApproveAdditional.defaultProps = {
  additionalVisible: false,
  selectedData: [],
  quickTxt: '',
  onClose: () => {},
  entities: {},
  customFormPropertyMap: {}
};

function mapStateToProps(state) {
  return {}
}

const wrappedApproveAdditional = Form.create()(ApproveAdditional);
export default connect(mapStateToProps)(wrappedApproveAdditional);
